<script lang="ts">
  import "./editor.css";
  import type { Action } from "svelte/action";
  import EditorJS, { type OutputData } from "@editorjs/editorjs";
  import Header from "@editorjs/header";
  import List from "@editorjs/list";

  interface EditorProps {
    sizeClass: string;
    placeholder?: string;
    data?: string;
    readOnly?: boolean;
    onInit?: (editor: EditorJS) => void;
  }

  let props: EditorProps = $props();

  const editorAction: Action = (node) => {
    $effect(() => {
      let data: OutputData | undefined = undefined;
      if (props.data != undefined && props.data != "") {
        try {
          data = JSON.parse(props.data) as OutputData;
        } catch (e) {
          console.log(e);
        }
      }
      const tmpEditor = new EditorJS({
        holder: node,
        placeholder: props.placeholder,
        data: data,
        inlineToolbar: false,
        readOnly: props.readOnly,
        tools: {
          header: Header,
          list: List,
        },
        i18n: {
          messages: {
            ui: {
              blockTunes: {
                toggler: {
                  "Click to tune": "点击进行调整",
                },
              },
              popover: {
                Filter: "过滤",
                "Convert to": "转换",
              },
              toolbar: {
                toolbox: {
                  Add: "增加",
                },
              },
            },
            toolNames: {
              Text: "文本",
              Heading: "标题",
              "Unordered List": "无序列表",
              "Ordered List": "有序列表",
              Checklist: "检查列表",
            },
            tools: {
              header: {
                "Heading 1": "标题1",
                "Heading 2": "标题2",
                "Heading 3": "标题3",
                "Heading 4": "标题4",
                "Heading 5": "标题5",
                "Heading 6": "标题6",
              },
              list: {
                Unordered: "无序列表",
                Ordered: "有序列表",
                Checklist: "检查列表",
              },
            },
            blockTunes: {
              delete: {
                Delete: "删除",
              },
              moveUp: {
                "Move up": "向上移动",
              },
              moveDown: {
                "Move down": "向下移动",
              },
            },
          },
        },
      });
      tmpEditor.isReady.then(() => {
        if (props.onInit != undefined) {
          props.onInit(tmpEditor);
        }
        node.onclick = (e) => {
          e.preventDefault();
        };
      });
      return () => {
        if (tmpEditor.destroy) {
          tmpEditor.destroy();
        }
      };
    });
  };
</script>

<div
  use:editorAction
  tabindex="-10"
  class={`bg-surface-100-900 ${props.sizeClass} overflow-y-auto overflow-x-hidden pl-[30px] break-all`}
></div>
